import asyncio,json
ip, port, ammo = "127.0.0.1", 1046, 0
reflections = {"0": 0,"1": 1,"2": 2,"3": 3}
def input_operation(players):
    """
    input operation
    """
    global ammo
    operation, target = input("输入操作："), dict()
    while True:
        if operation in reflections.keys():
            operation = reflections[operation]
            if operation == 2:
                while True:
                    target_player=input(str(list(enumerate(players,start=1)))+":")
                    if target_player not in [str(i) for i in range(1,len(players)+1)]:break
                    try:target_ammo = int(input("对应弹量："))
                    except ValueError:break
                    if 0 > target_ammo or target_ammo > ammo:break
                    target[players[int(target_player)-1]] = target_ammo
                    ammo -= target_ammo
            elif operation == 0:ammo += 1
            break
        operation = input("重新输入：")
    return operation, target
async def client(pos, host):
    global ammo
    reader, writer = await asyncio.open_connection(pos, host)
    while True:
        name = input("name:")
        writer.write(name.encode())
        await writer.drain()
        statu = await reader.read(100)
        if statu != b"\x01":break
    dead = 1
    while True:
        ammo = 0
        if statu == b"\x00":
            input("start game:")
            writer.write(b"\x00")
            await writer.drain()
            statu = await reader.read(100)
        players = json.loads(statu.decode())
        while True:
            if dead == 0:
                response = (-1, 0)
            else:
                response = input_operation(players)
            writer.write(json.dumps(response).encode())
            await writer.drain()
            data = json.loads((await reader.read(1024)).decode())
            print("收到结果：", data)
            players = list(data.keys())
            dead = data[name][2]
            if dead == 2 or dead == 3:
                print("本局结束\n")
                break
        answer = input("是否继续：")
        if answer == "是" or answer == "y":
            writer.write(b"\x01")
            await writer.drain()
            statu = await reader.read(100)
        else:
            writer.write(b"\x02")
            await writer.drain()
            break
asyncio.run(client(ip, port))